package com.liukaixin.product.ru.business.team.teamdesc;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.TextInputLayout;
import android.support.v4.app.Fragment;
import android.support.v4.widget.NestedScrollView;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.jude.easyrecyclerview.EasyRecyclerView;
import com.jude.easyrecyclerview.adapter.RecyclerArrayAdapter;
import com.liukaixin.product.ru.R;
import com.liukaixin.product.ru.business.competition.competitionlist.CompetitionsAdapter;
import com.liukaixin.product.ru.business.notice.NoticesActivity;
import com.liukaixin.product.ru.business.user.editUser.EditUserActivity;
import com.liukaixin.product.ru.business.user.login.LoginActivity;
import com.liukaixin.product.ru.data.model.Apply;
import com.liukaixin.product.ru.data.model.Favorite;
import com.liukaixin.product.ru.data.model.Team;
import com.liukaixin.product.ru.data.model.TeamMember;
import com.liukaixin.product.ru.data.model.User;
import com.liukaixin.product.ru.enumerate.ApplyStatusEnum;
import com.liukaixin.product.ru.enumerate.FavoriteTypeEnum;
import com.liukaixin.product.ru.enumerate.NoticeTypeEnum;
import com.liukaixin.product.ru.util.CheckUtil;
import com.liukaixin.product.ru.util.LVCircularSmile;
import com.orhanobut.logger.Logger;

import java.util.List;

import static com.google.common.base.Preconditions.checkNotNull;

/**
 * Created by Jacob on 2016/9/19.
 */
public class TeamDescFragment extends Fragment implements TeamDescContract.View,
        View.OnClickListener {

    @NonNull
    private static final String ARGUMENT_TEAM_ID = "TEAM_ID";
    @NonNull
    private static final String ARGUMENT_CREATOR_ID = "CREATOR_ID";
    @NonNull
    private static final String ARGUMENT_TEAM_NAME = "TEAM_NAME";
    @NonNull
    private static final String ARGUMENT_COMPETITION_NAME = "COMPETITION_NAME";

    // 显示"已提申请"
    public static final Integer CHECK = 1;
    // 显示"已加团队"
    public static final Integer AGREE = 2;
    // 显示"已被拒绝"
    public static final Integer REJECT = 3;
    // 显示"加入团队"
    public static final Integer JOIN = 4;
    // 显示"审核申请"
    public static final Integer CHECK_APPLY = 5;

    private TeamDescContract.Presenter presenter;

    private NestedScrollView scrollView;

//    private TextView schoolText;
//    private TextView userNickNameText;
    private TextView originatorIntroText;
    private TextView teamIntroText;
//    private TextView mottoText;
    private TextView requireText;
    private TextView numberText;
    private TextView competitionNameText;

    // "加入团队""已提申请""已经加入""已被拒绝"按钮
    private FloatingActionButton plusFab;
    // 收藏按钮
    private FloatingActionButton favoriteFab;

    private LVCircularSmile smileLoading;

    private boolean isFavorite = false;
    // 被其他团队同意的状态,默认0(未取服务),1(被其他同意)
    private Integer agreeStatus = 0;

    private User user = CheckUtil.isLogin();

    private Team team;

    private EasyRecyclerView recyclerView;

    private TeamMembersAdapter teamMembersAdapter;

    public TeamDescFragment() {
        // Required an empty constructor
    }

    public static TeamDescFragment newInstance(@Nullable Integer teamId,
                                               @Nullable Integer creatorId,
                                               @Nullable String teamName,
                                               @Nullable String competitionName) {
        Bundle arguments = new Bundle();
        arguments.putInt(ARGUMENT_TEAM_ID, teamId);
        arguments.putInt(ARGUMENT_CREATOR_ID, creatorId);
        arguments.putString(ARGUMENT_TEAM_NAME, teamName);
        arguments.putString(ARGUMENT_COMPETITION_NAME, competitionName);
        TeamDescFragment fragment = new TeamDescFragment();
        fragment.setArguments(arguments);
        return fragment;
    }

    @Override
    public void setPresenter(TeamDescContract.Presenter presenter) {
        this.presenter = checkNotNull(presenter);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_team_desc, container, false);
        setHasOptionsMenu(true);
        setRetainInstance(true);
        return root;
    }

    // 初始化视图.
    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        smileLoading = (LVCircularSmile) view.findViewById(R.id.lv_circularSmile);
        scrollView = (NestedScrollView) view.findViewById(R.id.nested_scroll);

//        schoolText = (TextView) view.findViewById(R.id.school_text);
//        userNickNameText = (TextView) view.findViewById(R.id.user_nick_name_text);
        originatorIntroText = (TextView) view.findViewById(R.id.originator_intro_text);
        teamIntroText = (TextView) view.findViewById(R.id.intro_edit);
//        mottoText = (TextView) view.findViewById(R.id.motto_text);
        requireText = (TextView) view.findViewById(R.id.require_text);
        numberText = (TextView) view.findViewById(R.id.number_text);
        competitionNameText = (TextView) view.findViewById(R.id.competition_name_text);

        plusFab = (FloatingActionButton) view.findViewById(R.id.plus_fab);
        plusFab.setOnClickListener(this);

        favoriteFab = (FloatingActionButton) getActivity().findViewById(R.id.favorite_fab);
        favoriteFab.setOnClickListener(this);

        teamMembersAdapter = new TeamMembersAdapter(getActivity());
        // Set up the competitions view
        recyclerView = (EasyRecyclerView) view.findViewById(R.id.recycler_view);
        recyclerView.setLayoutManager(new LinearLayoutManager(getActivity(),
                LinearLayoutManager.HORIZONTAL, false));

        recyclerView.setAdapterWithProgress(teamMembersAdapter);
        recyclerView.setItemAnimator(new DefaultItemAnimator());

        teamMembersAdapter.setOnItemClickListener(
                this::toTeamMemberActivity);
        // 取团队详情.
        presenter.getTeamDescById();
    }

    private void toTeamMemberActivity(Integer position) {
        AlertDialog.Builder builder =
                new android.support.v7.app.AlertDialog.Builder(getActivity());
        builder.setTitle("成员简介");
        builder.setMessage(teamMembersAdapter.getItem(position).getExpert());
        builder.setNegativeButton("确定", null);
        builder.show();
    }

    // 唤醒时.
    @Override
    public void onResume() {
        super.onResume();

    }

    @Override
    public void showLoading() {
        smileLoading.setVisibility(View.VISIBLE);
        smileLoading.startAnim();
    }

    @Override
    public void hideLoading() {
        smileLoading.setVisibility(View.GONE);
        smileLoading.stopAnim();
    }

    @Override
    public void showErrorToast(String msg) {
        Toast.makeText(getActivity(), msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void showData(Team team) {
//        schoolText.setText(team.getSchool());
        competitionNameText.setText(team.getCompetitionName());
//        userNickNameText.setText(team.getUserNickName());
        originatorIntroText.setText("学校：" + team.getSchool() + "\n"
                + "昵称：" + team.getUserNickName() + "\n"
                + "能力：" + team.getCreatorIntro());
        teamIntroText.setText(team.getIntro());
//        mottoText.setText(team.getMotto());
        requireText.setText(team.getRequire());
        numberText.setText(String.valueOf(team.getNumber()));
    }

    @Override
    public void showScrollView() {
        scrollView.setVisibility(View.VISIBLE);
    }


    @Override
    public void makeFavorited() {
        isFavorite = true;
        favoriteFab.setVisibility(View.VISIBLE);
        favoriteFab.setImageResource(R.drawable.have_favorite);
    }

    @Override
    public void makeUnFavorited() {
        isFavorite = false;
        favoriteFab.setVisibility(View.VISIBLE);
        favoriteFab.setImageResource(R.drawable.favorite);
    }

    @Override
    public void haveAgreeByOthers() {
        agreeStatus = 1;
    }

    @Override
    public void checkPersonalInfo() {
        user = CheckUtil.isLogin();
        if (user.getNickName() == null || user.getNickName().isEmpty()) {
            toEditUserActivity();
            return;
        }
        if (user.getSchool() == null || user.getSchool().isEmpty()) {
            toEditUserActivity();
            return;
        }
        if (user.getMajor() == null || user.getMajor().isEmpty()) {
            toEditUserActivity();
            return;
        }
        writeApply();
    }

    @Override
    public void showPlusTab(Integer typeCode) {
        plusFab.setVisibility(View.VISIBLE);
        switch (typeCode) {
            // 未审核
            case 1:
                plusFab.setImageResource(R.drawable.have_applied);
                plusFab.setTag(CHECK);
                break;
            // 同意
            case 2:
                plusFab.setImageResource(R.drawable.have_join_team_tab);
                plusFab.setTag(AGREE);
                break;
            // 拒绝
            case 3:
                plusFab.setImageResource(R.drawable.have_reject);
                plusFab.setTag(REJECT);
                break;
            case 4:
                plusFab.setImageResource(R.drawable.join_team_tab);
                plusFab.setTag(JOIN);
                break;
            case -1:
                plusFab.setImageResource(R.drawable.join_team_tab);
                plusFab.setTag(JOIN);
                break;
            default:
                plusFab.setImageResource(R.drawable.check_apply);
                plusFab.setTag(CHECK_APPLY);
                break;
        }
    }

    @Override
    public void setTeam(Team team) {
        this.team = team;
        // 判断登录状态.
        user = CheckUtil.isLogin();
        if (user != null) {
            // 判断是不是自己的团队.如果不是自己的团队,再获取申请状态.
            presenter.whoseTeam(team.getUserId(), user.getId());
            // 如果登录,获取收藏状态.
            presenter.getFavoriteStatus(user.getId());
        } else {
            // 如果未登录,显示加入团队按钮.
            plusFab.setVisibility(View.VISIBLE);
            // 显示未收藏
            makeUnFavorited();
        }
    }

    @Override
    public void getTeamMembers() {
        Logger.d("获取团队成员们：teamId = %d", team.getId());
        presenter.getTeamMembers(team.getId());
    }

    @Override
    public void showNoData() {
        recyclerView.showEmpty();
    }

    @Override
    public void showTeamMembers(List<TeamMember> teamMembers) {
        teamMembersAdapter.addAll(teamMembers);
        teamMembersAdapter.notifyDataSetChanged();
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.plus_fab:
                joinFabClicked();
                break;
            case R.id.favorite_fab:
                favoriteFabClicked();
                break;
            default:
                break;
        }
    }

    private void toNoticeActivity() {
        Intent toNoticeActivity = new Intent(getActivity(), NoticesActivity.class);
        toNoticeActivity.putExtra(NoticesActivity.EXTRA_CATEGORY_ID,
                NoticeTypeEnum.TEAM_NOTICE.getTypeCode());
        startActivity(toNoticeActivity);
    }

    private void writeApply() {
        LayoutInflater inflater = getActivity().getLayoutInflater();
        View dialog = inflater.inflate(R.layout.dialog_apply,
                (ViewGroup) getActivity().findViewById(R.id.dialog));
        EditText editText = (EditText) dialog.findViewById(R.id.ability_edit);
        EditText contactEdit = (EditText) dialog.findViewById(R.id.contact_edit);
        TextInputLayout abilityTil = (TextInputLayout) dialog.findViewById(R.id.ability_til);
        TextInputLayout contactTil = (TextInputLayout) dialog.findViewById(R.id.contact_til);
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("申请");
        builder.setPositiveButton("确定", (dialog1, which) -> {
            String ability = editText.getText().toString().trim();
            String contact = contactEdit.getText().toString().trim();
            if (ability.isEmpty()) {
                abilityTil.setError("不能为空");
            } else if (contact.isEmpty()) {
                contactTil.setError("不能为空");
            } else {
                Apply apply = new Apply(ability, user.getId(),
                        TeamDescFragment.this.getArguments().getInt(ARGUMENT_TEAM_ID),
                        TeamDescFragment.this.getArguments().getInt(ARGUMENT_CREATOR_ID));
                apply.setCompetitionName(team.getCompetitionName());
                apply.setTeamName(team.getName());
                apply.setApplyUserContact(contact);
                presenter.sendApply(apply);
            }
        });
        builder.setNegativeButton("取消", null);
        builder.setView(dialog);
        builder.show();
    }

    private void favoriteFabClicked() {
        if (user != null) {
            if (isFavorite) {
                Toast.makeText(getActivity(), "取消收藏", Toast.LENGTH_SHORT).show();
                presenter.cancelFavorite(user.getId());
            } else {
                Toast.makeText(getActivity(), "收藏", Toast.LENGTH_SHORT).show();
                Favorite favorite = new Favorite();
                favorite.setCategory(FavoriteTypeEnum.TEAM.getTypeCode());
                favorite.setStarId(TeamDescFragment.this.getArguments().getInt(ARGUMENT_TEAM_ID));
                favorite.setUserId(user.getId());
                favorite.setStarName(
                        TeamDescFragment.this.getArguments().getString(ARGUMENT_TEAM_NAME));
                presenter.doFavorite(favorite);
            }
        } else {
            toLoginActivity();
        }
    }

    private void joinFabClicked() {
        if (plusFab.getTag() == null || plusFab.getTag().equals(JOIN)) {
            if (user != null) {
                if (agreeStatus == 0) {
                    presenter.getOtherApplyStatus(user.getId(),
                            team.getCompetitionName());
                } else if (agreeStatus == 1) {
                    Toast.makeText(getActivity(),
                            "您已参与该比赛的其他团队\n不能再申请加入该团队", Toast.LENGTH_SHORT).show();
                }
            } else {
                toLoginActivity();
            }
        } else if (plusFab.getTag().equals(CHECK)) {
            Toast.makeText(getActivity(), "您已提交申请,请耐心等候~", Toast.LENGTH_SHORT).show();
        } else if (plusFab.getTag().equals(AGREE)) {
            // do nothing
        } else if (plusFab.getTag().equals(REJECT)) {
            Toast.makeText(getActivity(),
                    "天涯何处无芳草,去看看别的团队吧~", Toast.LENGTH_SHORT).show();
        } else if (plusFab.getTag().equals(CHECK_APPLY)) {
            toNoticeActivity();
        }
    }

    private void toLoginActivity() {
        Intent toLogin = new Intent(getContext(), LoginActivity.class);
        startActivity(toLogin);
    }

    private void toEditUserActivity() {
        AlertDialog.Builder builder =
                new android.support.v7.app.AlertDialog.Builder(getActivity());
        builder.setTitle("提示");
        builder.setMessage("为了双方的安全,需要补充个人信息后才能申请加入团队");
        builder.setNegativeButton("取消", null);
        builder.setPositiveButton("去补充", (dialog1, which) -> {
            Intent intent = new Intent(getActivity(), EditUserActivity.class);
            startActivity(intent);
        });
        builder.show();
    }

}